package org.jeecg.modules.zcgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgBaseController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.ConvertUpMoney;
import org.jeecg.common.util.CurrencyUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ReflectHelper;
import org.jeecg.modules.message.service.ISysMessageTemplateService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecg.modules.zcgl.entity.*;
import org.jeecg.modules.zcgl.enums.LeaseContractStatusEnum;
import org.jeecg.modules.zcgl.enums.ModeOfPaymentTypeEnum;
import org.jeecg.modules.zcgl.service.*;
import org.jeecg.modules.zcgl.vo.ContractPrintVo;
import org.jeecg.modules.zcgl.vo.LeaseContractInfoPage;
import org.jeecg.modules.zcgl.vo.LeaseContractRenewVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 合同信息
 * @Author: jeecg-boot
 * @Date: 2020-06-20
 * @Version: V1.0
 */
@Api(tags = "合同信息")
@RestController
@RequestMapping("/zcgl/leaseContractInfo")
@Slf4j
public class LeaseContractInfoController extends JeecgBaseController<LeaseContractInfoPage, LeaseContractInfo, ILeaseContractInfoService> {

    @Autowired
    private ILeaseContractInfoService leaseContractInfoService;
    @Autowired
    private ICustomerInfoService customerInfoService;
    @Autowired
    private IAssetInfoService assetInfoService;
    @Autowired
    private IAssetInfoSubService assetInfoSubService;
    @Autowired
    private ISysMessageTemplateService sysMessageTemplateService;
    @Autowired
    private ISysDictService dictService;
    @Autowired
    private SysBaseApiImpl baseApi;
    @Autowired
    private ILeaseContractStandardRentService leaseContractStandardRentService;
    @Autowired
    private ILeaseContractContentService leaseContractContentService;
    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 分页列表查询
     *
     * @param leaseContractInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "合同信息-分页列表查询")
    @ApiOperation(value = "合同信息-分页列表查询", notes = "合同信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(LeaseContractInfo leaseContractInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Map<String, String[]> parameterMap = new HashMap(req.getParameterMap());
        parameterMap.remove("managerId");
        parameterMap.remove("regional");
        QueryWrapper<LeaseContractInfo> queryWrapper = QueryGenerator.initQueryWrapper(leaseContractInfo, parameterMap);

        if (StringUtils.isNotBlank(req.getParameter("managerId"))) {
            queryWrapper.lambda().inSql(LeaseContractInfo::getAssetId, "SELECT asset.id FROM zcgl_asset_info AS asset WHERE asset.manager_id = '" + req.getParameter("managerId") + "'");
        }
        if (StringUtils.isNotBlank(req.getParameter("regional"))) {
            queryWrapper.lambda().inSql(LeaseContractInfo::getAssetId, "SELECT asset.id FROM zcgl_asset_info AS asset WHERE asset.regional = '" + req.getParameter("regional") + "'");
        }

        Page<LeaseContractInfo> page = new Page<LeaseContractInfo>(pageNo, pageSize);
        IPage<LeaseContractInfo> pageList = leaseContractInfoService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param leaseContractInfoPage
     * @return
     */
    @AutoLog(value = "合同信息-添加")
    @ApiOperation(value = "合同信息-添加", notes = "合同信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LeaseContractInfoPage leaseContractInfoPage) {
        leaseContractInfoService.saveMain(leaseContractInfoPage);
        return Result.ok("添加成功！");
    }


    /**
     * 添加
     *
     * @param vo
     * @return
     */
    @AutoLog(value = "合同信息-更新打印模版ID")
    @ApiOperation(value = "合同信息-更新打印模版ID", notes = "合同信息-更新打印模版ID")
    @PostMapping(value = "/updatePrintTemplateId")
    public Result<?> updatePrintTemplateId(@RequestBody LeaseContractInfo vo) {
        if (StringUtils.isBlank(vo.getPrintTemplateId())) {
            return Result.errorValidation("合同模版信息错误！");
        }
        if (sysMessageTemplateService.getById(vo.getPrintTemplateId()) == null) {
            return Result.errorValidation("合同模版信息错误！");
        }
        LeaseContractInfo leaseContractInfo = service.getById(vo.getId());
        if (leaseContractInfo == null) {
            return Result.errorValidation("合同信息错误！");
        }
        leaseContractInfo.setPrintTemplateId(vo.getPrintTemplateId());
        leaseContractInfoService.updateById(leaseContractInfo);
        return Result.ok("更新成功！");
    }

    /**
     * 编辑
     *
     * @param leaseContractInfoPage
     * @return
     */
    @AutoLog(value = "合同信息-编辑")
    @ApiOperation(value = "合同信息-编辑", notes = "合同信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LeaseContractInfoPage leaseContractInfoPage) {
        LeaseContractInfo leaseContractInfoEntity = leaseContractInfoService.getById(leaseContractInfoPage.getId());
        if (leaseContractInfoEntity == null) {
            return Result.error("未找到对应数据");
        }
        leaseContractInfoService.updateMain(leaseContractInfoPage);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同信息-通过id删除")
    @ApiOperation(value = "合同信息-通过id删除", notes = "合同信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        leaseContractInfoService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同信息-批量删除")
    @ApiOperation(value = "合同信息-批量删除", notes = "合同信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.leaseContractInfoService.delBatchMain(Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR)));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同信息-通过id查询")
    @ApiOperation(value = "合同信息-通过id查询", notes = "合同信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(id);
        if (leaseContractInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(leaseContractInfo);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同分段租金信息表通过主表ID查询")
    @ApiOperation(value = "合同分段租金信息表主表ID查询", notes = "合同分段租金信息表-通主表ID查询")
    @GetMapping(value = "/queryLeaseContractStandardRentByMainId")
    public Result<?> queryLeaseContractStandardRentListByMainId(@RequestParam(name = "id", required = true) String
                                                                        id) {
        List<LeaseContractStandardRent> leaseContractStandardRentList = leaseContractStandardRentService.selectByMainId(id);
        return Result.ok(leaseContractStandardRentList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同信息打印信息-通过id查询")
    @ApiOperation(value = "合同信息打印信息-通过id查询", notes = "合同信息打印信息-通过id查询")
    @GetMapping(value = "/queryPrintById")
    public Result<?> queryPrintById(@RequestParam(name = "id", required = true) String id) {
        LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(id);
        if (leaseContractInfo == null) {
            return Result.error("未找到对应数据");
        }

        //查询是否已生成打印信息，如果已生成直接返回生成的打印信息
        LeaseContractContent contractContent = leaseContractContentService.selectByLeaseContractIdAndPrintTemplateId(leaseContractInfo.getId(), leaseContractInfo.getPrintTemplateId());
        if (contractContent != null) {
            return Result.ok(contractContent.getContractContent(), "");
        }

        DecimalFormat df = new DecimalFormat("###,##0.00");

        ContractPrintVo vo = new ContractPrintVo();

        if (StringUtils.isNotBlank(leaseContractInfo.getCustomerId())) {
            List<CustomerInfo> customerInfos = (List<CustomerInfo>) customerInfoService.listByIds(Arrays.asList(leaseContractInfo.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR)));
            StringBuilder customerNameSb = new StringBuilder();
            StringBuilder addressSb = new StringBuilder();
            StringBuilder codeSb = new StringBuilder();
            StringBuilder phoneSb = new StringBuilder();
            if (customerInfos != null) {
                customerInfos.forEach(customerInfo -> {
                    customerNameSb.append(customerInfo.getName() + CommonConstant.DEFAULT_SEPARATOR);
                    if (!codeSb.toString().contains(customerInfo.getCode())) {
                        codeSb.append(customerInfo.getCode() + CommonConstant.DEFAULT_SEPARATOR);
                    }
                    if(customerInfo.getContactAddress() != null){
                        if (!addressSb.toString().contains(customerInfo.getContactAddress())) {
                            addressSb.append(customerInfo.getContactAddress() + CommonConstant.DEFAULT_SEPARATOR);
                        }
                    }
                    if (!phoneSb.toString().contains(customerInfo.getPhone())) {
                        phoneSb.append(customerInfo.getPhone() + CommonConstant.DEFAULT_SEPARATOR);
                    }
                });
                codeSb.deleteCharAt(codeSb.length() - 1);
                customerNameSb.deleteCharAt(customerNameSb.length() - 1);
                if(addressSb !=null  && addressSb.length()>0){
                    addressSb.deleteCharAt(addressSb.length() - 1);
                }
                phoneSb.deleteCharAt(phoneSb.length() - 1);
            }
            vo.setCustomerName(customerNameSb.toString());
            vo.setAddress(addressSb.toString());
            vo.setCode(codeSb.toString());
            vo.setPhone(phoneSb.toString());
        }
//        CustomerInfo customerInfos = customerInfoService.getById(leaseContractInfo.getCustomerId());
//        if (customerInfo != null) {
//            vo.setCustomerName(customerInfo.getName());
//            vo.setAddress(customerInfo.getAddress());
//            vo.setCode(customerInfo.getCode());
//            vo.setPhone(customerInfo.getPhone());
//        }

//        AssetInfo assetInfos = assetInfoService.getById(leaseContractInfo.getAssetId());
        StringBuilder sb = new StringBuilder();
        AtomicInteger num = new AtomicInteger();

        if (StringUtils.isNotBlank(leaseContractInfo.getAssetId())) {
            List<AssetInfo> assetInfoList = (List<AssetInfo>) assetInfoService.listByIds(Arrays.asList(leaseContractInfo.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR)));
            if (assetInfoList != null) {
                for (AssetInfo assetInfo : assetInfoList) {
                    if (StringUtils.isBlank(leaseContractInfo.getAssetSubIds())) {
                        sb.append(assetInfo.getSite() + CommonConstant.DEFAULT_SEPARATOR);
                        num.getAndIncrement();
                        continue;
                    }

                    List<AssetInfoSub> assetInfoSubList = assetInfoSubService.selectByMainIdAndIds(assetInfo.getId(), leaseContractInfo.getAssetSubIds());
                    if (assetInfoSubList == null || assetInfoSubList.size() == 0) {
                        sb.append(assetInfo.getSite() + CommonConstant.DEFAULT_SEPARATOR);
                        num.getAndIncrement();
                        continue;
                    }
                    sb.append(assetInfo.getSite());
                    assetInfoSubList.forEach(sub -> {
                        num.getAndIncrement();
                        sb.append(sub.getRoomName() + "、");
                    });
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(CommonConstant.DEFAULT_SEPARATOR);
                }
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        vo.setSite(sb.toString());
        vo.setNum(num.toString());

//        LambdaQueryWrapper<ReceivablesInfo> qw = new LambdaQueryWrapper<>();
//        qw.eq(ReceivablesInfo::getLeaseContractId, leaseContractInfo.getId());
//        qw.eq(ReceivablesInfo::getPaymentInstructions, PaymentInstructionsEnum.RENT.getStatus());
//        qw.orderByAsc(ReceivablesInfo::getStartTime);
//        qw.last("limit 1");
//        ReceivablesInfo receivablesInfo = receivablesInfoService.getOne(qw);
//        if (receivablesInfo != null) {
//            vo.setAmountMoney(df.format(receivablesInfo.getAmountMoney()));
//            vo.setStartTime(DateUtils.formatDate(receivablesInfo.getStartTime()));
//            vo.setEndTime(DateUtils.formatDate(receivablesInfo.getEndTime()));
//        }

//        qw = new LambdaQueryWrapper<>();
//        qw.eq(ReceivablesInfo :: getLeaseContractId, leaseContractInfo.getId());
//        qw.eq(ReceivablesInfo :: getPaymentInstructions, PaymentInstructionsEnum.CAUTION_MONEY.getStatus());
//        qw.orderByAsc(ReceivablesInfo :: getStartTime);
//        qw.last("limit 1");
//
//        ReceivablesInfo deposit = receivablesInfoService.getOne(qw);
//        if (deposit != null && receivablesInfo.getAmountMoney() != null){
//            vo.setDepositAmountMoney(df.format(deposit.getAmountMoney()));
//            vo.setDepositAmountMoneyCN(ConvertUpMoney.toChinese(vo.getDepositAmountMoney()) + "整");
//        } else {
//            vo.setDepositAmountMoneyCN("\\");
//            vo.setDepositAmountMoney("\\");
//        }

        vo.setContractNum(leaseContractInfo.getContractNum());
        vo.setSigningDate(DateUtils.formatDate(leaseContractInfo.getSigningDate() != null ? leaseContractInfo.getSigningDate() : new Date()));
        vo.setRentableArea(df.format(leaseContractInfo.getRentableArea()== null ? 0.00 : leaseContractInfo.getRentableArea()));
        vo.setRentPrice(df.format(leaseContractInfo.getRentPrice() == null ? 0.00 : leaseContractInfo.getRentPrice()));
        if (StringUtils.isNumeric(leaseContractInfo.getContractPeriod())) {
            vo.setContractPeriod(leaseContractInfo.getContractPeriod() + "年");
        } else {
            vo.setContractPeriod(leaseContractInfo.getContractPeriod());
        }
        vo.setRentStartTime(DateUtils.formatDate(leaseContractInfo.getRentStartTime()));
        vo.setRentEndTime(DateUtils.formatDate(leaseContractInfo.getRentEndTime()));
        vo.setMonthlyRent(df.format(leaseContractInfo.getMonthlyRent() ==null?BigDecimal.ZERO:leaseContractInfo.getMonthlyRent()));
        vo.setLiquidatedDamages(leaseContractInfo.getLiquidatedDamages() == null ? "\\" : df.format(leaseContractInfo.getLiquidatedDamages()));
        vo.setRentHolidayStart(leaseContractInfo.getRentHolidayStart() != null ? DateUtils.formatDate(leaseContractInfo.getRentHolidayStart()) : "\\");
        vo.setRentHolidayEnd(leaseContractInfo.getRentHolidayEnd() != null ? DateUtils.formatDate(leaseContractInfo.getRentHolidayEnd()) : "\\");
        vo.setModeOfPayment(ModeOfPaymentTypeEnum.getName(leaseContractInfo.getModeOfPayment()));
        vo.setBeforeDay(String.valueOf(leaseContractInfo.getBeforeDay()));

        vo.setSupplementaryTerms(leaseContractInfo.getSupplementaryTerms() == null
                ? "" : "补充条款：\n" + leaseContractInfo.getSupplementaryTerms());


        Date startDate = leaseContractInfo.getRentHolidayEnd() != null ? DateUtils.nextDay(leaseContractInfo.getRentHolidayEnd(), 1) : leaseContractInfo.getRentStartTime();
        Date endDate = DateUtils.nextDay(DateUtils.nextMonth(startDate, ModeOfPaymentTypeEnum.getMonth(leaseContractInfo.getModeOfPayment())), -1);
        int m = ModeOfPaymentTypeEnum.getMonth(leaseContractInfo.getModeOfPayment());
        BigDecimal leaseAmountMoney = leaseContractInfo.getMonthlyRent().multiply(new BigDecimal(m));
        if (DateUtils.sameDate(endDate, leaseContractInfo.getRentEndTime()) > 0) {
            int d = DateUtils.daysBetween(startDate, endDate);
            endDate = leaseContractInfo.getRentEndTime();
            int d1 = DateUtils.daysBetween(startDate, endDate);
            leaseAmountMoney = leaseAmountMoney.divide(new BigDecimal(d), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(d1));
            if (leaseAmountMoney.compareTo(BigDecimal.ZERO) <= 0) {
                leaseAmountMoney = new BigDecimal(0.01);
            }
        }

        vo.setAmountMoney(df.format(leaseAmountMoney));
        vo.setStartTime(DateUtils.formatDate(startDate));
        vo.setEndTime(DateUtils.formatDate(endDate));

        if (leaseContractInfo.getManageStatus() != null) {
//            Field field = leaseContractInfo.getClass().getDeclaredField(LeaseContractInfo :: getManageStatus)
            vo.setManageStatus(dictService.queryDictTextByKey("zcgl_manage_status", String.valueOf(leaseContractInfo.getManageStatus())));
        } else {
            vo.setManageStatus("");
        }
        vo.setDepositAmountMoneyPayDate("签订合同时");
        vo.setNum(String.valueOf(num.get()));

        if (leaseContractInfo.getCashDeposit() != null) {
            vo.setDepositAmountMoney(df.format(leaseContractInfo.getCashDeposit()));
            vo.setDepositAmountMoneyCN(ConvertUpMoney.toChinese(leaseContractInfo.getCashDeposit().toString()) + "整");
        } else {
            vo.setDepositAmountMoneyCN("\\");
            vo.setDepositAmountMoney("\\");
        }
//        Map<String, Object> voMap = BeanUtils.beanToMap(vo);
//        Map<String,String> newMap = new HashMap<String,String>();
//        for (Map.Entry<String, Object> entry : voMap.entrySet()) {
//            if(entry.getValue() instanceof String){
//                newMap.put(entry.getKey(), entry.getValue() != null ? String.valueOf(entry.getValue()) : "");
//            }
//        }

        List<SysDepart> departList = sysDepartService.list();
        Optional<SysDepart> rentCompany = departList.stream().filter(p -> p.getId().equals(leaseContractInfo.getRentCompanyId())).findAny();
        if (rentCompany.isPresent()) {
            vo.setRentCompanyName(rentCompany.get().getDepartName());
        }

        Optional<SysDepart> companyName = departList.stream().filter(p -> p.getId().equals(leaseContractInfo.getCompanyId())).findAny();
        if (companyName.isPresent()) {
            vo.setCompanyName(companyName.get().getDepartName());
        }

        vo.setMonthlyRentBig(CurrencyUtil.bigDecimalToLocalStr(leaseContractInfo.getMonthlyRent()==null?new BigDecimal(0.00):leaseContractInfo.getMonthlyRent()));
        vo.setDepositAmountMoneyBig(CurrencyUtil.bigDecimalToLocalStr(leaseContractInfo.getCashDeposit()==null?new BigDecimal(0.00):leaseContractInfo.getCashDeposit()));


        Map<String, Object> newMap = ReflectHelper.objectToMap(vo);
        String content = baseApi.parseTemplateById(leaseContractInfo.getPrintTemplateId(), newMap);

//        List<SysMessageTemplate> sysSmsTemplates = sysMessageTemplateService.selectByCode("houses_rental_contract");
//        if(sysSmsTemplates==null||sysSmsTemplates.size()==0){
//            return Result.error("房屋租赁合同模版不存在");
//        }
//        SysMessageTemplate sysSmsTemplate = sysSmsTemplates.get(0);
//        //模板内容
//        String content = sysSmsTemplate.getTemplateContent();
        return Result.ok(content, "");
    }


    /**
     * @param vo
     * @return
     */
    @AutoLog(value = "合同信息-打印更新打印信息")
    @ApiOperation(value = "合同信息-打印更新打印信息", notes = "合同信息-打印更新打印信息")
    @PostMapping(value = "/updatePrint")
    public Result<String> updatePrint(@RequestBody LeaseContractContent vo) {

        LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(vo.getLeaseContractId());
        if (leaseContractInfo == null) {
            return Result.error("合同信息查询失败！");
        }
        LeaseContractContent leaseContractContent = new LeaseContractContent();
        leaseContractContent.setContractContent(vo.getContractContent());
        leaseContractContent.setLeaseContractId(leaseContractInfo.getId());
        leaseContractContent.setPrintTemplateId(leaseContractInfo.getPrintTemplateId());
        leaseContractContentService.saveCheck(leaseContractContent);
        return Result.ok();
    }


    /**
     * @param id
     * @return
     */
    @AutoLog(value = "合同信息-合同生效审批验证")
    @ApiOperation(value = "合同信息-合同生效审批验证", notes = "合同信息-合同生效审批验证")
    @PostMapping(value = "/takeEffectApproval")
//    @ApiImplicitParam
    public Result<String> takeEffectApproval(@RequestParam(name = "id", required = true) String id) {

        LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(id);
        if (leaseContractInfo == null) {
            return Result.error("未找到对应数据");
        }
        if (leaseContractInfo.getStatus() != null && leaseContractInfo.getStatus().intValue() != 10) {
            return Result.error("合同不是未生效");
        }

        List<LeaseContractStandardRent> leaseContractStandardRentList = leaseContractStandardRentService.selectByMainId(leaseContractInfo.getId());
        LeaseContractInfoPage page = new LeaseContractInfoPage();
        BeanUtils.copyProperties(leaseContractInfo, page);
        page.setLeaseContractStandardRentList(leaseContractStandardRentList);
        //校验数据
        service.checkModel(page);
        return Result.ok();
    }


    /**
     * @param vo
     * @return
     */
    @AutoLog(value = "合同信息-合同生效")
    @ApiOperation(value = "合同信息-合同生效", notes = "合同信息-合同生效")
    @PostMapping(value = "/takeEffect")
    public Result<?> takeEffect(LeaseContractRenewVo vo) {
        if (vo.getSigningDate() == null) {
            return Result.error("请选择合同签约日期");
        }
        LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(vo.getId());
        if (leaseContractInfo == null) {
            return Result.error("未找到对应数据");
        }
        if (leaseContractInfo.getStatus() != null && leaseContractInfo.getStatus().intValue() != 10) {
            return Result.error("合同不是未生效");
        }

        List<LeaseContractStandardRent> leaseContractStandardRentList = leaseContractStandardRentService.selectByMainId(vo.getId());
        LeaseContractInfoPage page = new LeaseContractInfoPage();
        BeanUtils.copyProperties(leaseContractInfo, page);
        page.setLeaseContractStandardRentList(leaseContractStandardRentList);
        page.setStatus(LeaseContractStatusEnum.TAKE_EFFECT.getStatus());
        page.setSigningDate(vo.getSigningDate());
        leaseContractInfoService.takeEffect(page);
        return Result.ok();
    }

    /**
     * 批量生效
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同信息-批量生效")
    @ApiOperation(value = "合同信息-批量生效", notes = "合同信息-批量生效")
    @GetMapping(value = "/batchTakeEffect")
    public Result<?> batchTakeEffect(@RequestParam(name = "ids", required = true) String ids) {

        int success = 0;
        int fail = 0;
        List<String> idsList = Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR));
        for (int i = 0; i < idsList.size(); i++) {
            LeaseContractInfo leaseContractInfo = leaseContractInfoService.getById(idsList.get(i));
            if (leaseContractInfo.getSigningDate() == null) {
                //return Result.error(leaseContractInfo.getContractNum()+"合同未填写签约日期，请先填写签约日期或手动点击生效!");
                fail += 1;
                continue;
            }

            if (leaseContractInfo == null) {
                //return Result.error("未找到对应数据!");
                fail += 1;
                continue;
            }
            if (leaseContractInfo.getStatus() != null && leaseContractInfo.getStatus().intValue() != 10) {
                //return Result.error(leaseContractInfo.getContractNum()+"合同不是未生效!");
                fail += 1;
                continue;
            }
            try {
                List<LeaseContractStandardRent> leaseContractStandardRentList = leaseContractStandardRentService.selectByMainId(idsList.get(i));
                LeaseContractInfoPage page = new LeaseContractInfoPage();
                BeanUtils.copyProperties(leaseContractInfo, page);
                page.setLeaseContractStandardRentList(leaseContractStandardRentList);
                page.setStatus(LeaseContractStatusEnum.TAKE_EFFECT.getStatus());
                //page.setSigningDate(vo.getSigningDate());
                leaseContractInfoService.takeEffect(page);
                success += 1;

            } catch (Exception e) {
                fail += 1;
                continue;
            }
        }

        return Result.ok("成功：" + success + "条！失败：" + fail + "条！");
    }


    /**
     * @return
     */
    @AutoLog(value = "合同信息-合同生效")
    @ApiOperation(value = "合同信息-合同生效", notes = "合同信息-合同生效")
    @PermissionData("takeEffectAll")
    @PostMapping(value = "/takeEffectAll")
    public Result<?> takeEffectAll() {
        QueryWrapper<LeaseContractInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(LeaseContractInfo::getStatus, LeaseContractStatusEnum.DRAFT.getStatus());
        queryWrapper.apply("DATE(rent_end_time) < DATE('" + DateUtils.now() + "')");
        List<LeaseContractInfo> contractInfoList = leaseContractInfoService.list(queryWrapper);
        //查询已结束的合同，生效后结束合同
        contractInfoList.stream().forEach(c -> {
            try {
                this.a(c);
//                assetInfoService.updateAssetForRentStatus(c.getAssetId(), c.getAssetSubIds());
                LeaseContractRenewVo vo = new LeaseContractRenewVo();
                vo.setId(c.getId());
                vo.setStatus(LeaseContractStatusEnum.TERMINATE.getStatus());
                service.updateStatus(vo);
            } catch (Exception e) {
                log.error("生成已结束的合同失败：", e);
            }
        });

        QueryWrapper<LeaseContractInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(LeaseContractInfo::getStatus, LeaseContractStatusEnum.DRAFT.getStatus());
//        queryWrapper1.apply("DATE(rent_start_time) < DATE('"+DateUtils.now()+"')");
        List<LeaseContractInfo> contractInfoList1 = leaseContractInfoService.list(queryWrapper1);
        //查询正常的合同生效
        contractInfoList1.stream().forEach(c -> {
            try {
                this.a(c);
            } catch (Exception e) {
                log.error("生成合同失败：", e);
            }
        });
        return Result.ok();
    }

    private void a(LeaseContractInfo vo) {

        List<LeaseContractStandardRent> leaseContractStandardRentList = leaseContractStandardRentService.selectByMainId(vo.getId());
        LeaseContractInfoPage page = new LeaseContractInfoPage();
        BeanUtils.copyProperties(vo, page);
        page.setLeaseContractStandardRentList(leaseContractStandardRentList);
        page.setStatus(LeaseContractStatusEnum.TAKE_EFFECT.getStatus());
        page.setSigningDate(vo.getSigningDate());
        leaseContractInfoService.takeEffect(page);

    }

    /**
     * @param vo
     * @return
     */
    @AutoLog(value = "合同信息-续签合同验证数据")
    @ApiOperation(value = "合同信息-续签合同验证数据", notes = "合同信息-续签合同验证数据")
    @PostMapping(value = "/renewCheckModel")
    public Result<?> renewCheckModel(@RequestBody LeaseContractRenewVo vo) {
        if (vo.getEndDate() == null) {
            return Result.error("续签的到期日期必须填写");
        }
        leaseContractInfoService.renewCheckModel(vo);
        return Result.ok();
    }

    /**
     * @param vo
     * @return
     */
    @AutoLog(value = "合同信息-续签合同")
    @ApiOperation(value = "合同信息-续签合同", notes = "合同信息-续签合同")
    @PostMapping(value = "/renew")
    public Result<?> renew(@RequestBody LeaseContractRenewVo vo) {
        if (vo.getEndDate() == null) {
            return Result.error("续签的到期日期必须填写");
        }
        leaseContractInfoService.renew(vo);
        return Result.ok();
    }

    /**
     * 合同信息变更
     *
     * @param leaseContractInfoPage
     * @return
     */
    @AutoLog(value = "合同信息变更")
    @ApiOperation(value = "合同信息变更", notes = "合同信息变更")
    @PutMapping(value = "/modify")
    public Result<?> modify(@RequestBody LeaseContractInfoPage leaseContractInfoPage) {
        service.modify(leaseContractInfoPage);
        return Result.ok("变更成功！");
    }

    /**
     * 检测数据是否正常
     *
     * @param leaseContractInfoPage
     * @return
     */
    @AutoLog(value = "合同信息变更-检测数据是否正常")
    @ApiOperation(value = "合同信息变更-检测数据是否正常", notes = "合同信息变更-检测数据是否正常")
    @PostMapping(value = "/modifyCheckModel")
    public Result<?> modifyCheckModel(@RequestBody LeaseContractInfoPage leaseContractInfoPage) {
        service.modifyCheckModel(leaseContractInfoPage);
        return Result.ok("检测通过！");
    }

    /**
     * 检测数据是否正常
     *
     * @param leaseContractInfoPage
     * @return
     */
    @AutoLog(value = "合同信息-检测数据是否正常")
    @ApiOperation(value = "合同信息-检测数据是否正常", notes = "合同信息-检测数据是否正常")
    @PostMapping(value = "/checkModel")
    public Result<?> checkModel(@RequestBody LeaseContractInfoPage leaseContractInfoPage) {
        service.checkModel(leaseContractInfoPage);
        return Result.ok("检测通过！");
    }

    /**
     * @return
     */
    @AutoLog(value = "合同信息-状态修改检测")
    @ApiOperation(value = "合同信息-状态修改检测", notes = "合同信息-状态修改检测")
    @PostMapping(value = "/updateStatusCheck")
    public Result<?> updateStatusCheck(LeaseContractRenewVo vo) {
        leaseContractInfoService.updateStatusCheck(vo);
        return Result.ok();
    }

    /**
     * @return
     */
    @AutoLog(value = "合同信息-退租")
    @ApiOperation(value = "合同信息-退租", notes = "合同信息-退租")
    @PostMapping(value = "/surrender")
    public Result<?> surrender(LeaseContractRenewVo vo) {
        vo.setStatus(LeaseContractStatusEnum.SURRENDER.getStatus());
        leaseContractInfoService.updateStatus(vo);
        return Result.ok();
    }

    /**
     * @return
     */
    @AutoLog(value = "合同信息-结束")
    @ApiOperation(value = "合同信息-结束", notes = "合同信息-结束")
    @PostMapping(value = "/terminate")
    public Result<?> terminate(LeaseContractRenewVo vo) {
        vo.setRent(BigDecimal.ZERO);
//        vo.setCashDeposit(BigDecimal.ZERO);
        vo.setStatus(LeaseContractStatusEnum.TERMINATE.getStatus());
        leaseContractInfoService.updateStatus(vo);
        return Result.ok();
    }

    /**
     * @param vo
     * @return
     */
    @AutoLog(value = "合同信息-终止合同")
    @ApiOperation(value = "合同信息-终止合同", notes = "合同信息-终止合同")
    @PostMapping(value = "/termination")
    public Result<?> termination(LeaseContractRenewVo vo) {
        vo.setStatus(LeaseContractStatusEnum.TERMINATION.getStatus());
        leaseContractInfoService.updateStatus(vo);
        return Result.ok();
    }

    /**
     * 导出excel
     *
     * @param request
     * @param leaseContractInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LeaseContractInfo leaseContractInfo) {
        return super.exportXls(request, leaseContractInfo, LeaseContractInfoPage.class, "合同信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LeaseContractInfoPage.class);
    }

    @Override
    public List<LeaseContractInfoPage> exportList(List<LeaseContractInfo> list) {
        List<LeaseContractInfoPage> pages = new ArrayList<>();
        if (list != null) {
            list.stream().forEach(item -> {
                LeaseContractInfoPage vo = new LeaseContractInfoPage();
                BeanUtils.copyProperties(item, vo);
                List<LeaseContractStandardRent> assetInfoSubList = leaseContractStandardRentService.selectByMainId(item.getId());
                vo.setLeaseContractStandardRentList(assetInfoSubList);
//				vo.setAssetImageList(assetImageService.selectByMainId(main.getId()));
                pages.add(vo);
            });
        }
        return pages;
    }


    @Override
    public boolean importSave(LeaseContractInfoPage vo) {
        leaseContractInfoService.importSaveMain(vo);
        return true;
    }
}
